<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="采购单号" prop="ordersNumber">
        <el-input
          v-model="queryParams.ordersNumber"
          placeholder="请输入计划单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="id">
        <treeselect
          v-model="queryParams.id"
          :options="vendorOptions"
          :show-count="true"
          placeholder="请输入供应商"
          style="width: 210px"
        />
      </el-form-item>
      &nbsp;
      <el-form-item label="付款状态" prop="advanceStatus">
        <el-select
          v-model="queryParams.advanceStatus"
          placeholder="请选择付款状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.advance_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-finished"
          size="mini"
          :disabled="multiple"
          @click="handlePayment"
          v-hasPermi="['finance:advance:applicant']"
          >批量付款</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleApproved"
          v-hasPermi="['finance:advance:applicant']"
          >核准</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleOverrule"
          v-hasPermi="['finance:advance:applicant']"
          >驳回</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['finance:advance:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="advanceList"
      @selection-change="handleSelectionChange"
      ref="myTable"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商编号" align="center" prop="vendorNumber" />
      <el-table-column label="供应商名称" align="center" prop="name">
        <template slot-scope="scope">
          <span v-if="scope.row.name">
            {{ scope.row.name.slice(0, 10) }}
            <span v-if="scope.row.name.length > 10">...</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
      <el-table-column label="预付金额" align="center" prop="requestAmount" />
      <el-table-column label="货币" align="center" prop="monetaryName" />
      <el-table-column label="申请人" align="center" prop="applicant" />
      <el-table-column
        label="申请日期"
        align="center"
        prop="applicationDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="advanceStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.advance_status"
            :value="scope.row.advanceStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="requestRemark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'finance:advance:edit',
              'finance:advance:applicant',
              'finance:advance:applicant',
            ]"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >更多</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleUpdate"
                icon="el-icon-edit"
                v-hasPermi="['finance:advance:edit']"
                v-if="scope.row.advanceStatus == 0"
                >修改</el-dropdown-item
              >
              <el-dropdown-item
                command="handleOverrule"
                icon="el-icon-close"
                v-hasPermi="['finance:advance:applicant']"
                v-if="scope.row.advanceStatus == 0"
                >驳回</el-dropdown-item
              >
              <el-dropdown-item
                command="handlePayment"
                icon="el-icon-finished"
                v-hasPermi="['finance:advance:applicant']"
                v-if="
                  scope.row.applicant != null && scope.row.advanceStatus == 0
                "
                >付款</el-dropdown-item
              >
              <el-dropdown-item
                command="handleQuash"
                icon="el-icon-document-delete"
                v-hasPermi="['finance:advance:query']"
                v-if="scope.row.advanceStatus == 1"
                >查看</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预付款对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商:" prop="name">
              {{ form.name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购单号:" prop="ordersNumber">
              {{ form.ordersNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款金额:" prop="requestAmount">
              <el-input
                v-model="form.requestAmount"
                placeholder="请输入付款金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="货币:" prop="monetaryName">
              {{ form.monetaryName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人:" prop="applicant">
              {{ form.applicant }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期:" prop="requestAmount">
              {{ parseTime(form.requestAmount, "{y}-{m}-{d}") }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款状态:" prop="advanceStatus">
              <template v-if="form.advanceStatus == 0">未付款</template>
              <template v-else>已生成付款单</template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="requestRemark">
              <el-input
                v-model="form.requestRemark"
                placeholder="请输入备注"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情页 -->
    <el-dialog
      :title="titleView"
      :visible.sync="openView"
      width="800px"
      append-to-body
    >
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商:" prop="name">
              {{ form.name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购单号:" prop="ordersNumber">
              {{ form.ordersNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款金额:" prop="requestAmount">
              {{ form.requestAmount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="货币:" prop="monetaryName">
              {{ form.monetaryName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人:" prop="applicant">
              {{ form.applicant }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期:" prop="requestAmount">
              {{ parseTime(form.requestAmount, "{y}-{m}-{d}") }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款状态:" prop="advanceStatus">
              <template v-if="form.advanceStatus == 0">未付款</template>
              <template v-else>已生成付款单</template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="requestRemark">
              {{ form.requestRemark }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitView">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAdvance,
  getAdvance,
  updateAdvance,
  getUpdateAdvanceApplicant,
  getSelectAdvanceByRequestId,
  getUpdateAdvanceByAdvanceStatus,
  getUpdateRequestAdvanceCancelStatus,
  getUpdateRequestAdvancePaymentStatus,
  getInsertPaymentSlipsList,
} from "@/api/finance/advance";
import { getRequestAdvanceByRequestId } from "@/api/orders/ProcuredOrders";
import { getSelectVendorTreeList } from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Advance",
  dicts: ["advance_status"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idss: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预付款表格数据
      advanceList: [],
      // 弹出层标题
      title: "",
      titleView: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advanceStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 供应商
      vendorOptions: [],
    };
  },
  created() {
    this.getList();
    this.getVendor();
  },
  methods: {
    /** 查询预付款列表 */
    getList() {
      this.loading = true;
      listAdvance(this.queryParams).then((response) => {
        this.advanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        advanceId: null,
        requestId: null,
        advanceStatus: null,
        applicant: null,
        applicationDate: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.requestId);
      this.idss = selection.map((item) => item.advanceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预付款";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const requestId = row.requestId || this.ids;
      getAdvance(requestId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预付款";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateAdvance(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "finance/advance/export",
        {
          ...this.queryParams,
        },
        `advance_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    /**核准按钮 */
    handleApproved(row) {
      const requestIds = row.requestId || this.ids;
      this.$modal
        .confirm("您确认所选数据将核准吗？")
        .then(function () {
          getUpdateRequestAdvanceCancelStatus(requestIds);
          return getUpdateAdvanceApplicant(requestIds, true);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("核准成功!");
        })
        .catch(() => {});
    },
    /** 驳回 */
    handleOverrule(row) {
      const requestIds = row.requestId || this.ids;
      this.$modal
        .confirm("您确定将所选记录驳回吗？")
        .then(function () {
          getRequestAdvanceByRequestId(requestIds);
          return getUpdateAdvanceApplicant(requestIds, false);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("驳回成功!");
        })
        .catch(() => {});
    },
    /** 批量付款 */
    handlePayment(row) {
      const requestIds = row.requestId || this.ids;
      const advanceIds = row.advanceId || this.idss;
      this.$modal
        .confirm("您确定付款所选数据吗？（付款将生成付款单）")
        .then(() => {
          // 调用接口获取选择的数据

          return getSelectAdvanceByRequestId(requestIds);
        })
        .then((response) => {
          var index = 0;
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i].advanceStatus == 1) {
              this.$modal.msgWarning(
                "所选记录含有已生成付款单记录，请重新选择"
              );
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            }
            if (response.data[i].applicant == null) {
              this.$modal.msgError("所选记录含有部分数据没有核准，请重新选择");
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            }
          }
          if (index == 0) {
            getInsertPaymentSlipsList(response.data);
            getUpdateRequestAdvancePaymentStatus(requestIds);
            return getUpdateAdvanceByAdvanceStatus(requestIds);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("付款成功!");
        })
        .catch(() => {});
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleOverrule":
          this.handleOverrule(row);
          break;
        case "handlePayment":
          this.handlePayment(row);
          break;
        case "handleQuash":
          this.handleQuash(row);
          break;
        default:
          break;
      }
    },
    /** 查看详情页 */
    handleQuash(row) {
      this.reset();
      const requestId = row.requestId || this.ids;
      getAdvance(requestId).then((response) => {
        this.form = response.data;
        this.titleView = "预付款查看";
        this.openView = true;
      });
    },
    /**详情确定按钮 */
    submitView() {
      this.openView = false;
    },
  },
};
</script>
